package ext.acae2.change;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import wt.change2.WTChangeOrder2;
import wt.fc.PersistenceHelper;
import wt.lifecycle.LifeCycleManaged;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.project.Role;
import wt.team.Team;
import wt.team.TeamHelper;
import wt.team.TeamReference;
import wt.util.WTException;

import com.ptc.windchill.enterprise.team.server.TeamCCHelper;

import ext.acae2.ACAEConstants;
import ext.acae2.utilities.principal.CSCPrincipal;
import ext.acae2.utilities.util.CSCUtil;

/**
 * @desription TODO
 * @author cnie
 * @date 2013-6-19 上午10:54:36
 */
public class TestAddPrincipalsToTeam {
	
	
	public static void addTeamPrincipals(Object obj, Role role, List<WTUser> userList) {
		try {
			Team team=(Team)TeamCCHelper.getTeamFromObject((LifeCycleManaged)obj);
			if (team==null) {
    			return;
    		}
			boolean added=false;
			team=(Team)PersistenceHelper.manager.refresh(team);
			Vector objRoles=TeamHelper.service.findRoles(team);
			HashMap roleMap=TeamHelper.service.findAllParticipantsByRole(team);
			if (objRoles.contains(role)) {
				ArrayList principalList=(ArrayList)roleMap.get(role);
				for (WTUser user:userList) {
					boolean exists=false;
					for (int j=0; j<principalList.size(); j++) {
						WTPrincipal principal = (WTPrincipal) ((WTPrincipalReference)principalList.get(j)).getPrincipal();
						if (principal.equals(user)) {
							exists=true;
							break;
						}
					}
					if (!exists) {
						team.addPrincipal(role, user);
						added=true;
					}
				}
			} else {
				for (WTUser user:userList) {
					team.addPrincipal(role, user);   //如果生命周期中没有当前的角色，在当前对象的关联的生命周期增加该角色和user的信息
				}
				added=true;
			}
			if (added) {
				TeamReference teamreference = TeamReference.newTeamReference(team);
				TeamHelper.service.augmentRoles((LifeCycleManaged)obj, teamreference);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static void addPrincipalTest(String oid,String roleName) throws WTException{
		WTChangeOrder2 ecn = (WTChangeOrder2) CSCUtil.getObjectByOid(oid);
		Role role = Role.toRole(roleName);
		WTUser user = CSCPrincipal.getUserByName("cnie");
		List<WTUser> userList = new ArrayList<WTUser>();
		userList.add(user);
		addTeamPrincipals(ecn,role,userList);
	}
	
	public static void main(String[] args) throws WTException {
		addPrincipalTest("VR:wt.change2.WTChangeOrder2:270144",ACAEConstants.ROLE_BASELINEMANAGER);
	}
	
	

}
